<?php

namespace app\kefuapi\service;

use app\model\KefuChatLog;
use app\model\KefuConversation;
use app\model\KefuUser;
use app\model\SetSystem;
use app\model\User;
use app\service\ResponseService;
use Workerman\Connection\TcpConnection;
use Workerman\Worker;

class ChatService
{


    public array $connections = [];

    public array  $system;

    public string $module = '';

    public function __construct()
    {
        $this->system = SetSystem::getSystem();
    }

    public function onWorkerStart(Worker $worker){
        dump("启动成功");
    }
    public function onConnect(TcpConnection $connection){
        dump("连接成功");
    }

    /**
     * @throws \Exception
     */
    public function onMessage(TcpConnection $connection, $msg) {

        // 处理登录消息，登录的聊天对象有三种类型：游客、会员、客服，需要判断属于哪种类型

        $msgArr = json_decode($msg, true);


        if (!$msgArr['module']??'') {
            throw new \Exception("缺少module字段");
        }
        if (!$msgArr['type']??''){
            throw new \Exception("消息数据中缺少type字段");
        }

        $type = $msgArr['type'];
        $this->module = $msgArr['module'];
        if ($type == 'ping'){ // 回应客户端的心跳
            return $this->successSend($connection, ['module' => $this->module,'type' => $type]);
        }

        if ($this->module == 'kefu'){   // 客服聊天
            $ser = new KefuChatService($msgArr, $this, $connection);
            $res = $ser->handle();
        }

    }
    public function onClose(TcpConnection $connection){}
    public function onWorkerStop(TcpConnection $connection){}
    public function onWorkerReload(TcpConnection $connection){}

    public function onError(TcpConnection $connection, $code, $msg){
        dump("发生错误");
        dump($msg);
    }


    public function successSend(TcpConnection $connection, array $data): ?bool
    {

        $data = json_encode(makeSuccessResult($data));
        return $connection->send($data);
    }

    /**
     * @throws \Exception
     */
    public function errorSend(TcpConnection $connection, array $data, $error=1): ?bool
    {
        if (!$data['type']??''){
            throw new \Exception("消息数据中缺少type字段");
        }

        $data = json_encode(makeErrorResult($data, $error));
        return $connection->send($data);
    }

}
